package yana.tpe.onlineshop.domain.dao.impl;

import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.type.IntegerType;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;
import yana.tpe.onlineshop.domain.dao.ProductDao;
import yana.tpe.onlineshop.domain.domains.Product;

/**
 *
 */
@Repository
public class ProductDaoImpl extends AbstracDaoImpl<Integer, Product> implements ProductDao {

    @Override
    protected Class<Product> getDomainClass() {
        return Product.class;
    }

    @Override
    public List<Product> getProductFromCategory(final Integer categoryId) {
        List<Product> list;
        if (categoryId == null) {
            list = hibernateTemplate.find("FROM product WHERE category_id NOT IN ("
                    + "SELECT DISTINCT child.id FROM category node, IN(node.childs) child)");
        } else {
            list = hibernateTemplate.executeWithNativeSession(new HibernateCallback<List<Product>>() {

                @Override
                public List<Product> doInHibernate(Session session) throws HibernateException, SQLException {
                    Query query = session.createQuery("from product where category = :category");
                    query.setParameter("category", categoryId, new IntegerType());
                    return query.list();
                }
            });
        }
        flush();
        return list;
    }

    @Override
    public void delete(Integer id) {
        delete(get(id));
        flush();
    }
}
